package cn.sanli.manage.service.impl;

import cn.sanli.manage.mapper.data1.RewardsMapper;
import cn.sanli.manage.pojo.dto.Fault.FaultInfoStatisticsRequest;
import cn.sanli.manage.pojo.dto.Rewards.PageQueryOfRewardsRequest;
import cn.sanli.manage.pojo.dto.Rewards.RewardsInfoStatisticsRequest;
import cn.sanli.manage.pojo.dto.Rewards.RewardsInsertRequest;
import cn.sanli.manage.pojo.dto.Rewards.RewardsUpdateRequest;
import cn.sanli.manage.pojo.entity.Rewards;
import cn.sanli.manage.pojo.vo.Fault.FaultStatisticsInfoVO;
import cn.sanli.manage.pojo.vo.Fault.FaultStatisticsVO;
import cn.sanli.manage.pojo.vo.Rewards.RewardsStatisticsInfoVO;
import cn.sanli.manage.pojo.vo.Rewards.RewardsStatisticsVO;
import cn.sanli.manage.security.LoginPrincipal;
import cn.sanli.manage.service.RewardsService;
import cn.sanli.manage.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 奖励信息表(Rewards)表服务实现类
 *
 * @author wzy
 * @since 2023-12-07 16:06:49
 */
@Service("rewardsService")
@Slf4j
public class RewardsServiceImpl implements RewardsService {
    @Resource
    private RewardsMapper rewardsMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Rewards queryById(Integer id) {
        return rewardsMapper.queryById(id);
    }

    /**
     * 根据条件分页查询
     *
     * @param queryRequest 查询条件
     * @return 符合条件的数据
     */
    @Override
    public List<Rewards> pagingQuery(PageQueryOfRewardsRequest queryRequest) {
        return rewardsMapper.pagingQuery(queryRequest);
    }


    /**
     * 考核信息积分统计
     *
     * @return 结果集
     */
    @Override
    public List<RewardsStatisticsInfoVO> statisticsRewardsOfPersonage(LoginPrincipal loginPrincipal) {
        int roleId = loginPrincipal.getRoleId();
        log.debug("识别到的当事人: {}  主显权限: {}", loginPrincipal, roleId);
        // 分别获取本周,本月,本季,半年,本年的时间段
        Map<String, Date[]> statisticsTime = DateUtils.getStatisticsTime();

        // 声明一个请求参数封装类, 根据权限大小给查询条件实体类属性赋值
        RewardsInfoStatisticsRequest rewardsStatisticsRequest = new RewardsInfoStatisticsRequest();
        rewardsStatisticsRequest.setStartTime(statisticsTime.get(DateUtils.THISYEAR)[0]);
        rewardsStatisticsRequest.setEndTime(statisticsTime.get(DateUtils.THISYEAR)[1]);
        if(roleId == 1 || roleId == 2 || roleId==3 || roleId == 7) {

        } else if (roleId == 4) {
            rewardsStatisticsRequest.setCenter(loginPrincipal.centerId);
        } else if (roleId == 5 || roleId == 6){
            rewardsStatisticsRequest.setDept(loginPrincipal.getDeptId());
        }else {
//            statisticsRequest.setResNum(Integer.valueOf(loginPrincipal.getNum()));
            rewardsStatisticsRequest.setNum(Integer.valueOf("16766"));
        }

        // 根据查询条件搜索数据库
        List<RewardsStatisticsVO> rewardsStatisticsVOS
                = rewardsMapper.statisticsRewardsOfPersonage(rewardsStatisticsRequest);
        log.debug("根据条件获取到{}条数据", rewardsStatisticsVOS.size());
        log.debug("根据条件获取到的数据: {}", rewardsStatisticsVOS);

        // 以工号为key(), 当前对象为value存入map
        Map<String, List<RewardsStatisticsVO>> map = new HashMap<>();
        List<RewardsStatisticsVO> listOfMap = new ArrayList<>();
        for (RewardsStatisticsVO rewardsStatisticsVO : rewardsStatisticsVOS) {
            if(map.containsKey(rewardsStatisticsVO.getNum())) {
                listOfMap = map.get(rewardsStatisticsVO.getNum());
                listOfMap.add(rewardsStatisticsVO);
                map.put(rewardsStatisticsVO.getNum(), listOfMap);
            }else {
                List<RewardsStatisticsVO> list = new ArrayList<>();
                list.add(rewardsStatisticsVO);
                map.put(rewardsStatisticsVO.getNum(), list);
            }
        }

        // 创建List集合用于接受最终数据并返回
        List<RewardsStatisticsInfoVO> list = new ArrayList<>();
        // 遍历map集合, 调用数据统计方法
        for (String key : map.keySet()) {
            RewardsStatisticsInfoVO statisticsInfo = this.getStatisticsInfo(map.get(key), statisticsTime);
            log.debug("从map中获取key为{}的数据: {}", key, statisticsInfo);
            list.add(statisticsInfo);
        }
        log.debug("将统计完的数据集合返回: {}", list);

        // 返回
        return list;
    }


    private RewardsStatisticsInfoVO getStatisticsInfo(List<RewardsStatisticsVO> list, Map<String, Date[]> statisticsTime) {
        log.debug("调用getStatisticsInfo统计数据, 需处理的数据: {}  时间参数: {}", list, statisticsTime);
        RewardsStatisticsInfoVO rewardsStatisticsInfoVO = new RewardsStatisticsInfoVO();
        // 声明并初始化五个变量后续使用
        BigDecimal ofWeek = new BigDecimal("0.0");
        BigDecimal ofMonth = new BigDecimal("0.0");
        BigDecimal ofQuarter = new BigDecimal("0.0");
        BigDecimal ofHalf = new BigDecimal("0.0");
        BigDecimal ofYear = new BigDecimal("0.0");
        // 遍历数据集合
        for (RewardsStatisticsVO rewardsStatisticsVO : list) {
            log.debug("本次循环的数据: {}", rewardsStatisticsVO);
            // 根据考核时间判断
            if(rewardsStatisticsVO.getRewardsTime().getTime() >= statisticsTime.get(DateUtils.THISWEEK)[0].getTime()
                    &&
                    rewardsStatisticsVO.getRewardsTime().getTime() <= statisticsTime.get(DateUtils.THISWEEK)[1].getTime()) {
                ofWeek = ofWeek.add(rewardsStatisticsVO.getBonusPoints());
                ofMonth = ofMonth.add(rewardsStatisticsVO.getBonusPoints());
                ofQuarter = ofQuarter.add(rewardsStatisticsVO.getBonusPoints());
                ofHalf = ofHalf.add(rewardsStatisticsVO.getBonusPoints());
                ofYear = ofYear.add(rewardsStatisticsVO.getBonusPoints());
                continue;
            }else if(rewardsStatisticsVO.getRewardsTime().getTime() >= statisticsTime.get(DateUtils.THISMONTH)[0].getTime()
                    &&
                    rewardsStatisticsVO.getRewardsTime().getTime() <= statisticsTime.get(DateUtils.THISMONTH)[1].getTime()) {
                ofMonth = ofMonth.add(rewardsStatisticsVO.getBonusPoints());
                ofQuarter = ofQuarter.add(rewardsStatisticsVO.getBonusPoints());
                ofHalf = ofHalf.add(rewardsStatisticsVO.getBonusPoints());
                ofYear = ofYear.add(rewardsStatisticsVO.getBonusPoints());
                continue;
            }else if(rewardsStatisticsVO.getRewardsTime().getTime() >= statisticsTime.get(DateUtils.THISQUARTER)[0].getTime()
                    &&
                    rewardsStatisticsVO.getRewardsTime().getTime() <= statisticsTime.get(DateUtils.THISQUARTER)[1].getTime()) {
                ofQuarter = ofQuarter.add(rewardsStatisticsVO.getBonusPoints());
                ofHalf = ofHalf.add(rewardsStatisticsVO.getBonusPoints());
                ofYear = ofYear.add(rewardsStatisticsVO.getBonusPoints());
                continue;
            }else if(rewardsStatisticsVO.getRewardsTime().getTime() >= statisticsTime.get(DateUtils.THISHALF)[0].getTime()
                    &&
                    rewardsStatisticsVO.getRewardsTime().getTime() <= statisticsTime.get(DateUtils.THISHALF)[1].getTime()) {
                ofHalf = ofHalf.add(rewardsStatisticsVO.getBonusPoints());
                ofYear = ofYear.add(rewardsStatisticsVO.getBonusPoints());
                continue;
            }else if(rewardsStatisticsVO.getRewardsTime().getTime() >= statisticsTime.get(DateUtils.THISYEAR)[0].getTime()
                    &&
                    rewardsStatisticsVO.getRewardsTime().getTime() <= statisticsTime.get(DateUtils.THISYEAR)[1].getTime()) {
                ofYear = ofYear.add(rewardsStatisticsVO.getBonusPoints());
                continue;
            }
        }
        // 基本信息属性赋值
        rewardsStatisticsInfoVO.setName(list.get(0).getName());
        rewardsStatisticsInfoVO.setNum(list.get(0).getNum());
        rewardsStatisticsInfoVO.setDept(list.get(0).getDept());
        rewardsStatisticsInfoVO.setCenter(list.get(0).getCenter());
        // 积分信息赋值, 四舍五入保留一位小数
        rewardsStatisticsInfoVO.setStatisticsOfWeek(ofWeek.setScale(1, RoundingMode.HALF_UP));
        rewardsStatisticsInfoVO.setStatisticsOfMonth(ofMonth.setScale(1, RoundingMode.HALF_UP));
        rewardsStatisticsInfoVO.setStatisticsOfQuarter(ofQuarter.setScale(1, RoundingMode.HALF_UP));
        rewardsStatisticsInfoVO.setStatisticsOfHalf(ofHalf.setScale(1, RoundingMode.HALF_UP));
        rewardsStatisticsInfoVO.setStatisticsOfYear(ofYear.setScale(1, RoundingMode.HALF_UP));

        return rewardsStatisticsInfoVO;
    }

    /**
     * 新增数据
     *
     * @param rewardsInsertRequest 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public boolean insert(RewardsInsertRequest rewardsInsertRequest, LoginPrincipal loginPrincipal) {

        log.debug("开始处理新增奖励业务逻辑: {}", rewardsInsertRequest);
        // 截取字符串中的数字
        String maxRId = rewardsMapper.getMaxRId();
        String substring = maxRId.substring(1);
        log.debug("截取到的rid数值部分: {}", substring);
        // 数值加一生成新的rid并赋值
        rewardsInsertRequest.setRid("R" + (Integer.parseInt(substring) + 1));
        rewardsInsertRequest.setCreateName(loginPrincipal.getUserName());
        return rewardsMapper.insert(rewardsInsertRequest) > 0;
    }

    /**
     * 修改数据
     *
     * @param updateRequest 实例对象
     * @return 实例对象
     */
    @Override
    public boolean update(RewardsUpdateRequest updateRequest) {
        return rewardsMapper.update(updateRequest) > 0;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return rewardsMapper.deleteById(id) > 0;
    }
}
